'use strict';
const Koa = require('koa');
const config = require('../configs/config');
const vhost = require('../middlewares/virtual-host');
const morgan = require('../middlewares/morgan');
const compress = require('../middlewares/compress');
const userAgent = require('../middlewares/useragent');
const bodyParser = require('../middlewares/body-parser');
const ip = require('../middlewares/ip');
const serve = require('../middlewares/static');
const session = require('../middlewares/session');

const logger = require('../components/logger')(config.logger)('request');
const axios = require('../components/axios')({ logger: logger });

const app = new Koa();

if (config.vhost) {
  app.use(vhost(config.vhost));
}
app.use(ip());
app.use(morgan(config.logger));
app.use(compress());
if (config.static) {
  app.use(serve(config.static));
}
app.use(userAgent());
app.use(bodyParser());
if (config.session) {
  if (config.session.redis === true) {
    config.session.redis = config.redis;
  }
  app.use(session(config.session));
}

const Redis = require('ioredis');

app.use(async(ctx, next) => {
  ctx.session = "111";
  await next();
})
app.use(async(ctx) => {
  let redis = new Redis(6379, '192.168.3.108');
  let result = await axios.get('https://m.stb.nonobank.com/feserver/common/current');
  redis.set('test', JSON.stringify(result.data));
  ctx.body = {
    query: ctx.query,
    header: ctx.header,
    body: ctx.request.body,
    ip: ctx.request.ip,
    redis: await redis.get('test'),
    session: ctx.session,
    ua: ctx.userAgent
  };
});

app.listen(3000);

exports = module.exports = app;